'''
Author: meifeng mei.feng@asiainfo-sec.com
Date: 2023-10-17 17:07:29
LastEditors: meifeng mei.feng@asiainfo-sec.com
LastEditTime: 2023-10-18 16:39:57
FilePath: \admin_vue\src\express\express_app\py\mix.py
Description: 

Copyright (c) 2023 by ${meifeng}, All Rights Reserved. 
'''
from lxml.html import etree
import requests
from PIL import Image
import os
import sys
import argparse
from playwright.sync_api import sync_playwright



# 设置请求头
headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
}

# 命令行参数解析
parser = argparse.ArgumentParser()
parser.add_argument('--area', default='4kfengjing', help='类别')
parser.add_argument('--page', default=5, type=int, help='页数')
args = parser.parse_args()

area = args.area
page = args.page

# 创建下载目录
path = f'./py/image/{area}/{page}'
if not os.path.exists(path):
    os.makedirs(path)
# 类别映射
# area_mapping = {
#     '美女': '4kmeinv',
#     '风景': '4kfengjing',
#     '游戏': '4kyouxi',
#     # ... 添加其他类别映射
# }

# 确定类别
# if area in area_mapping:
#     area = area_mapping[area]
# else:
#     print('输入关键词格式不正确')
#     sys.exit(0)

# 创建 Playwright 实例
with sync_playwright() as p:
    browser = p.chromium.launch(headless=False, slow_mo=100)  # 打开浏览器
    context1 = browser.new_context()  # 创建浏览器上下文，支持创建多个上下文
    page1 = context1.new_page()
    if (page == 1):
        url = "http://pic.netbian.com/" + area + "/index.html"
        page1.goto(url)
        page1.click('.classify  a[href="/{}/"]'.format(area))
    if (page > 1):
        url = "http://pic.netbian.com/" + area + "/index_" + str(page) + ".html"
        page1.goto(url)
        page1.click('.page > a:last-child')
    # 点击下一页
    # for _ in range(1):
    #     page1.click('.page > a:last-child')

    # 等待页面加载完成
    page1.wait_for_load_state()

    # 获取图片链接
    img_urls = page1.query_selector_all('.slist > ul > li > a:first-child')
    url_list = [img_url.get_attribute('href') for img_url in img_urls]

    # 下载图片
for url in url_list:
    try:
        r = requests.get(url='http://pic.netbian.com' + url, headers=headers)
        r.encoding = r.apparent_encoding  # 修改编码

        html = etree.HTML(r.text)
        html = etree.tostring(html)
        html = etree.fromstring(html)

        img_url = html.xpath('//a[@id="img"]/img/@src')[0]
        img_name = html.xpath('//a[@id="img"]/img/@title')[0]
        image_path = f"{path}/{img_name}.png"
        if os.path.exists(image_path):
                    print("已有该图片")
                    continue
        rr = requests.get('http://pic.netbian.com' + img_url, headers=headers)
        rr.encoding = rr.apparent_encoding  # 修改编码

        with open(f"{path}/{img_name}.png", 'wb') as fw:
            fw.write(rr.content)

        img = Image.open(f"{path}/{img_name}.png")
        img = img.resize((4000, 2000), Image.Resampling.BILINEAR)  # 改变大小 抗锯齿
        img.save(f"{path}/{img_name}.png", quality=95)
        print(f"{img_name} 保存完成！")
    except Exception as e:
        print(f"处理 {url} 时出现异常：{str(e)}")
print("保存完成！")